package basics;

import js.Promise;
import pixi.plugins.wechat.Wechat;
import basics.ResultState.Callback;
import basics.data.AchievementVO;
import pixi.core.graphics.Graphics;
import basics.data.ChaperVO;
import framework.widgets.SpriteButton;
import pixi.core.textures.Texture;
import pixi.core.sprites.Sprite;
import pixi.core.text.DefaultStyle;
import pixi.core.text.Text;

class PlayState extends GameState{

	private var _textStyle:DefaultStyle;

	private var _fileChapter= "chapter.json";
	private var _fileAchievement= "achievement.json";

	// 關卡
	private var _txtLevel:Text;

	// 称号
	private var _txtAchievement:Text;

	// 汽車圖片
	private var _car:Sprite;

	// 輸入文字
	private var _textInput:Text;

	// 剩余时间
	private var _textTime:Text;

	// 问题
	private var _txtQue:Text;

	private var _txtOption1:Text;
	private var _txtOption2:Text;
	private var _txtOption3:Text;

	private var _options:Array<Text>;

	// 输入价格
	private var _price:Array<Int>;

	// 章节列表
	private var _chaperList:Array<ChaperVO>;

	// 成就
	private var _achievementList:Array<AchievementVO>;

	private var _curIndex:Int;
	private var _curLevel:ChaperVO;
	private var _curAchievement:AchievementVO;

	// 上次时间
	private var _lastTime:Float;
	private var _currTime:Float;
	private var _pause:Bool;

	// 错误提示
	private var _errorTip = [
		"是哪里不对呢？",
		"emmmmmmmmmmm.......,",
		"选哪个呢？",
		"选第一个还是第二个，这是一个问题！！",
		"或许第三个才是对的！！",
	];

	// 超时提示
	private var _timeoutTip = [
		"WTF?",
		"桃李春风一杯酒，江湖夜雨十年灯。",
		"天可补，海可填，南山可移。日月既往，不可复追。",
		"时光荏苒，岁月蹉跎。",
		"逝者如斯夫，不舍昼夜。",
	];

	public function new() {
		super(0);

		_lastTime = 0;
		_currTime = 0;
		_pause = true;
	}


	override public function onEnter():Void {
		trace("on play state");
		_textStyle = {};
		_textStyle.fontWeight = "bold";
		_textStyle.fontSize = 36;
		_textStyle.fontFamily = 'Arial';
		_textStyle.fill ='#FFFFFF';
		_textStyle.align = 'center';

		this.loadData();
	}



	override public function onExit():Void {

	}

	override public function onUpdate(dt:Float):Void {

		if(!_pause){
			_currTime = _currTime - dt / 1000;

			if(_currTime < 0){
				_currTime = 0;
				_pause = true;

				// 更新时间
				this.updateTime();
				// 计时结束
				this.showResult();
			}

			if(Math.abs(_lastTime - _currTime) >=1){
				this.updateTime();
				_lastTime = _currTime;
			}
		}
	}

	/**
	*	加載數據
	**/
	private function loadData(){

		var chaper:Dynamic = untyped __js__("require('./data/chapter.json')");
		var achievement:Dynamic  = untyped __js__("require('./data/achievement.json')");

		// 关卡数据
		_chaperList = new Array<ChaperVO>();
		var len = chaper.length;
		for( i in 0... len){
			var c:Dynamic = chaper[i];
			var vo = new ChaperVO();
			vo.id = c.id;
			vo.name	 = c.name;
			vo.desc = c.des;
			vo.time = c.time;
			vo.choice = c.choice;
			vo.question = c.question;

			var oplen = c.option.length;
			for(j in 0 ...oplen){
				vo.options.push(c.option[j]);
			}
			_chaperList.push(vo);
		}

		_curIndex = 0;
//		if(_chaperList.length > _currentIndex){
//			_currentVo = _chaperList[_currentIndex];
//			_currTime = _currentVo.time;
//			_lastTime = _currTime;
//		}

		// 成就数据
		_achievementList = new Array<AchievementVO>();
		len = achievement.length;
		for( i in 0... len){
			var c:Dynamic = achievement[i];
			var vo = new AchievementVO();
			vo.id = c.id;
			vo.name	 = c.name;
			vo.level = c.guess;
			_achievementList.push(vo);
		}

		this.showUI();
	}


	private function showUI(){

		//  logo
		var title = new Text("汽車猜猜猜", _textStyle);
		title.anchor.set(0.5);
		title.position.set(-140, -465);
		title.style.fontSize = 72;
		this.addChild(title);

		_txtLevel = new Text("第一关", _textStyle);
		_txtLevel.anchor.set(0.5);
		_txtLevel.position.set(200, -480);
		_txtLevel.style.fontSize = 56;
		this.addChild(_txtLevel);

		_txtAchievement = new Text("懂车行家", _textStyle);
		_txtAchievement.anchor.set(0.5);
		_txtAchievement.position.set(200, -420);
		_txtAchievement.style.fontSize = 46;
		this.addChild(_txtAchievement);

		// 背景框
		var frame = new Sprite(Texture.fromImage("assets/textures/game/frame.png"));
		frame.anchor.set(0.5);
		frame.position.set(0, -150);
		this.addChild(frame);

			// 汽車
		_car = new Sprite(Texture.fromImage("assets/textures/car/1.jpg"));
		_car.anchor.set(0.5);
		_car.position.set(0, 0);
		frame.addChild(_car);
		_car.mask = mask;

		// 倒计时
		_textTime = new Text("剩余时间:");
		_textTime.style = {
			fontSize: 28,
			fontFamily : 'Arial',
			fill : '#226ce8',
			align : 'left',
		};
		_textTime.anchor.set(1, 1);
		_textTime.position.set(310, 150);
		this.addChild(_textTime);

		// 问题
		_txtQue =  new Text("", _textStyle);
		_txtQue.anchor.set(0, 1);
		_txtQue.position.set(-310, 150);
		this.addChild(_txtQue);

		// 显示选项
		var btnOption1 = new SpriteButton(Texture.from("assets/textures/game/option.png"));
		btnOption1.onClick = function(){
			this.onChoice(1);
		};
		btnOption1.position.set(0, 230);
		this.addChild(btnOption1);

		var btnOption2 = new SpriteButton(Texture.from("assets/textures/game/option.png"));
		btnOption2.onClick = function(){
			this.onChoice(2);
		};
		btnOption2.position.set(0, 320);
		this.addChild(btnOption2);

		var btnOption3 = new SpriteButton(Texture.from("assets/textures/game/option.png"));
		btnOption3.onClick = function(){
			this.onChoice(3);
		};
		btnOption3.position.set(0, 410);
		this.addChild(btnOption3);

		_txtOption1 =  new Text("", _textStyle);
		_txtOption1.anchor.set(0.5, 0.5);
		btnOption1.addChild(_txtOption1);

		_txtOption2 =  new Text("", _textStyle);
		_txtOption2.anchor.set(0.5, 0.5);
		btnOption2.addChild(_txtOption2);

		_txtOption3 =  new Text("", _textStyle);
		_txtOption3.anchor.set(0.5, 0.5);
		btnOption3.addChild(_txtOption3);

		_options = new Array<Text>();
		_options.push(_txtOption1);
		_options.push(_txtOption2);
		_options.push(_txtOption3);


		this.showChaper(_curIndex);
	}


	/**
	* 显示章节
	**/
	private function showLevel(){
		if(_curLevel != null){
			var pic = "assets/textures/car/" + _curLevel.id + ".jpg";
			var texture = Texture.fromImage(pic);
			_car.texture = texture;
			_pause = false;

			// 关卡
			_txtLevel.text = "第 " + Std.string(_curLevel.id)+ " 关";
			_txtAchievement.text = _curAchievement.name;

			// 问题
			_txtQue.text = _curLevel.question;

			// 选项
			var n = _options.length;
			for(i in 0...n){
				var txtOption = _options[i];
				var text = _curLevel.options[i];
				if(text != null){
					txtOption.text = text;
					txtOption.parent.visible = true;
				}else{
					txtOption.parent.visible = false;
				}
			}

			this.updateTime();
		}
	}

	/**
	*	切换下一章
	**/
	private function showChaper(index:Int){
		if(index < _chaperList.length){
			// 获取关卡
			_curLevel = _chaperList[index];
			_currTime = _curLevel.time;


			// 获取成就
			for(vo in _achievementList){
				if(_curAchievement == null){
					_curAchievement = vo;
				}else{
					if(vo.level <  _curLevel.id && vo.level > _curAchievement.level){
						_curAchievement = vo;
					}
				}
			}

			this.showLevel();
		}else{
			var tip = new GameTips("恭喜你已经通关全部关卡!!!");
			this.addChild(tip);
		}
	}


	/**
	*	重置
	**/
	private function reset(){
		_curIndex = 0;
		this.showChaper(_curIndex);
	}


	/**
	*	时间结束
	**/
	private function showResult(){
		var n = Std.random(_timeoutTip.length);
		this.showResultDialog("时间到了", _timeoutTip[n], ["看视频", "从头开始"], function(idx:Int){
			this.reset();
		});
	}


	/**
	*	更新时间
	**/
	private function updateTime(){
		if(_curLevel != null){
			_textTime.text = "剩余时间: " + Math.ceil(_currTime);
		}
	}

	private function onChoice(index:Int):Void{
		_pause = true;

		if(index == _curLevel.choice){
			this.showResultDialog("猜对了", _curLevel.desc, ["下一关"], function(idx:Int){
				this.showChaper(_curIndex++);
			});
		}else{
			var n = _errorTip.length;
			var i = Std.random(n);
			this.showResultDialog("猜错了！", _errorTip[i], ["看视频", "从头开始"], function(idx:Int){
				trace("index", idx);
				if(idx == 0){
					this.showAd();
				}else{
					this.reset();
				}
			});
		}
	}

	/**
	*	显示提示
	**/
	private function showTip(msg:String){
		var tip = new GameTips(msg);
		this.addChild(tip);
	}


	/**
	*	显示对话框
	**/
	private function showResultDialog(title:String, msg:String, options:Array<String>, cb:Callback){
		var state = new ResultState(title,msg, options, cb);
		SceneManager.instance.pushState(state);
	}

	/**
	*	显示广告
	**/
	private function showAd():Void{
//		var ad = Wechat.createRewardedVideoAd({
//			adUnitId: "xxxx",
//		});
//		ad.onError(function(err:Dynamic){
//			trace("视频广告显示错误", err);
//		});
//		ad.onLoad(function(){
//			trace("视频广告显示成功");
//		});
//		ad.onClose(function(res:Dynamic){
//			// +1秒
//		});

	}
}
